package com.ghsc.ghxc.jsb.ui.live.activity

import android.Manifest
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import com.alibaba.sdk.android.oss.ClientException
import com.alibaba.sdk.android.oss.OSS
import com.alibaba.sdk.android.oss.ServiceException
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.alibaba.sdk.android.oss.model.PutObjectResult
import com.alivc.auicommon.common.base.callback.Callbacks
import com.alivc.auicommon.common.roombase.Const
import com.aliyun.aliinteraction.uikit.uibase.util.LastLiveSp
import com.aliyun.auipusher.LiveParam
import com.aliyun.auipusher.LiveRole
import com.aliyun.auipusher.config.AliLiveMediaStreamOptions
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideEngine
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.Preference
import com.cn.appcore.utils.TimeUtils
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.ApiService
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityLiveCreateBinding
import com.ghsc.ghxc.jsb.ui.live.view.CustLiveProtoType
import com.ghsc.ghxc.jsb.utils.OssUpUtils
import com.ghsc.ghxc.jsb.utils.StringUtil
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.permissionx.guolindev.PermissionX
import java.util.ArrayList

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.live.activity
 * 类名：LiveCreateActivity
 * 创建时间：2024/5/10 11:03
 * 创建人 @author： xiaolin
 * 描述 ：Todo... 创建直播
 */
class LiveCreateActivity : BaseVMActivity<LiveViewModel, ActivityLiveCreateBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_live_create
    }

    override fun attachVMClass(): Class<LiveViewModel>? {
        return LiveViewModel::class.java
    }

    val CHOOSE_PHOTO_2 = 1002
    private var selectBack: List<LocalMedia> = ArrayList()
    var pathBack = "" //
    private var themeId = 0

    //上传到阿里云服务器到图片url
    var aliUrlBackground = ""

    var userId: String by Preference(HttpConstant.USER_ID, "")
    var liveParam: LiveParam? = null
    var isClick: Boolean = false


    private val typeLive = 1 //直播类型 0 基础直播 1 连麦直播


    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }

    override fun initView() {
        binding.bar.topLeftView.setSingleClickListener {
            finish()
        }
        binding.bar.topTitle.text = "创建直播"
        themeId = R.style.picture_default_style
//        var confBean = UserManager.getConfig()
//        if (confBean!!.getIsLiveId()){
//            binding.llEx.visibility= View.VISIBLE
//        }else binding.llEx.visibility= View.GONE

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe { rxBusBean ->
                when {
                    rxBusBean.id == CustSignKey.LIVE_START_RUN && rxBusBean.sign == CustSignKey.LIVE_START_RUN -> {
                        this@LiveCreateActivity.dismissLoading()
                        this@LiveCreateActivity.finish()
                    }
//                    rxBusBean.id == CustSignKey.LIVE_START && rxBusBean.sign == CustSignKey.LIVE_START -> {
//                        this@LiveCreateActivity.dismissLoading()
//                        this@LiveCreateActivity.finish()
//                    }
                }
            }

//        val configBean= UserManager.getConfig()
//        configBean?.let {
//            aliUrlBackground=if (!TextUtils.isEmpty(it.getLiveConUrl())) it.getLiveConUrl() else ""
//            if (!TextUtils.isEmpty(aliUrlBackground)){
//                GlideUtil.ImageHeadLoad(this,aliUrlBackground,binding.imgBg)
//            }
//        }
    }


    override fun initData() {
        super.initData()

    }

    override fun initClickListener() {
        super.initClickListener()
        binding.tvBtnNext.setSingleClickListener {
            if (TextUtils.isEmpty(binding.etTitle.text)) {
                showToast("直播标题不能为空")
                return@setSingleClickListener
            }
            if (TextUtils.isEmpty(aliUrlBackground)) {
                showToast("请上传直播封面")
                return@setSingleClickListener
            }
            if (isClick) {
                showToast("当前已开始电脑obs推流")
                return@setSingleClickListener
            }
            PermissionX.init(this)
                .permissions(
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                )
                .request { allGranted, grantedList, deniedList ->
                    if (allGranted) {
                        showLoading()
                        gotoLivePage(null, Const.getUserId())
                    } else {
                        loge("当前权限授予="+grantedList.toString())
                        //弹出deniedList里面的被拒绝权限的提示
                        if (deniedList.contains(Manifest.permission.CAMERA)) {
                            showToast("请给相机权限")
                        } else if (deniedList.contains(Manifest.permission.RECORD_AUDIO)) {
                            showToast("请给录音权限")
                        } else if (deniedList.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            showToast("请给存储权限")
                        } else if (deniedList.contains(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                            showToast("请给存储权限")
                        } else {
                            showToast("请给相机、录音、存储权限")
                        }

                    }
                }


        }
        binding.imgBg.setOnClickListener {
            showPictures(CHOOSE_PHOTO_2)
        }
    }

    private fun showPictures(index: Int) {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage())
            .loadImageEngine(GlideEngine.createGlideEngine())
            .theme(themeId)
            .selectionMode(PictureConfig.SINGLE)
            .imageSpanCount(4)
            .previewImage(true)
            .isCamera(true)
            .enableCrop(false) // 是否裁剪
            .compress(true) // 是否压缩
            .freeStyleCropEnabled(true) // 裁剪框是否可拖拽
            .scaleEnabled(true)
//            .withAspectRatio(16, 9)
//                .cropWH(345,128)// 裁剪宽高比，设置如果大于图片本身宽高则无效
//                .cropImageWideHigh()//
            .minimumCompressSize(100) // 小于100kb的图片不压缩
            .forResult(index)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> when (requestCode) {
                CHOOSE_PHOTO_2 -> {
                    // 图片选择结果回调
                    selectBack = PictureSelector.obtainMultipleResult(data)
                    for (media in selectBack) {
                        Log.i("图片-----》", media.path)
                        pathBack = if (media.isCut && !media.isCompressed) {
                            // 裁剪过
                            media.cutPath
                        } else if (media.isCompressed || media.isCut && media.isCompressed) {
                            // 压缩过,或者裁剪同时压缩过,以最终压缩过图片为准
                            media.compressPath
                        } else {
                            // 原图
                            media.path
                        }
                        GlideUtil.ImageHeadLoad(this, pathBack, binding.imgBg)
                        //todo 上传背景
                        showLoading()
                        mViewModel.onAliYunOosMethod("")
                    }
                }
            }

            else -> {
            }
        }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@LiveCreateActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@LiveCreateActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onAliYunOosData.observe(this@LiveCreateActivity) {
                var oss = OssUpUtils.ossConfig(
                    this@LiveCreateActivity,
                    it.data.ossHost,
                    it.data.AccessKeyId,
                    it.data.AccessKeySecret,
                    it.data.SecurityToken
                )
                aliUrlBackground =
                    it.data.rootPATH + CustKey.IMG_URL_LIVE_COVER + StringUtil.getTime() + "/" + userId + TimeUtils.getTime10() + (0..100).random() + ".png"
                upload(oss, it.data.bucketName, pathBack, aliUrlBackground)
            }
        }
    }

    /**
     * bucketName 仓库名
     * uploadFilePath  阿里服务器的路径
     * objectName  图片地址
     */
    fun upload(oss: OSS, bucketName: String, objectName: String, uploadFilePath: String) {
        /**
         * bucketName
         * uploadFilePath 后台给的路径。是放在阿里服务器的某个路径下
         * objectName 本地上传的路径。比如上传的xxx/xxx/xxx.png
         */
        val put = PutObjectRequest(bucketName, uploadFilePath, objectName)
        // 异步上传时可以设置进度回调。
        put.progressCallback =
            OSSProgressCallback { request, currentSize, totalSize ->
            }
        val task: OSSAsyncTask<*> = oss.asyncPutObject(
            put,
            object : OSSCompletedCallback<PutObjectRequest?, PutObjectResult> {
                override fun onSuccess(request: PutObjectRequest?, result: PutObjectResult) {
                    loge("onSuccess-ETag" + result.eTag)
//                    loge("onSuccess-RequestId"+result.requestId)
//                    loge("onSuccess-result："+result.toString())
//                    loge("onSuccess-uploadFilePath"+request!!.uploadFilePath)
//                    loge("onSuccess-uploadUri"+request.uploadUri)
                    dismissLoading()
                    showToast("上传成功")
//                    aliUrlBackground = aliUrlBackground
                    aliUrlBackground= ApiService.ossImgUrl()+aliUrlBackground
//                    ApiService.ossImgUrl()+
                }

                override fun onFailure(
                    request: PutObjectRequest?,
                    clientExcepion: ClientException,
                    serviceException: ServiceException
                ) {
                    // 请求异常。
                    if (clientExcepion != null) {
                        // 客户端异常，例如网络异常等。
                        clientExcepion.printStackTrace()
                    }
                    if (serviceException != null) {
                        // 服务端异常。
                        Log.e("onFailure-ErrorCode", serviceException.errorCode)
                        Log.e("onFailure-RequestId", serviceException.requestId)
                        Log.e("onFailure-HostId", serviceException.hostId)
                        Log.e("onFailure-RawMessage", serviceException.rawMessage)
                    }
                    dismissLoading()
                    showToast("上传失败，请重试...")
                }
            })
//        取消上传任务。
//        task.cancel();
//        等待上传任务完成。
//        task.waitUntilFinished();
    }


    /**
     * 跳转直播页面
     *
     * @param liveId   直播Id
     * @param anchorId 主播Id
     */
    private fun gotoLivePage(liveId: String?, anchorId: String) {
        val param = CustLiveProtoType.OpenLiveParam()
        param.liveId = liveId
        param.nick = UserManager.getUserName()
        param.title = binding.etTitle.text.toString()
        param.notice = binding.etContent.text.toString()
        param.userAvatar = UserManager.getUserHead()
        param.model = typeLive
        param.cover = aliUrlBackground
        val callback = Callbacks.Lambda<String> { success, data, errorMsg ->
            if (success) {
                // 成功后, 记录该场直播, 便于下次快速进入
                val lastLiveSp = LastLiveSp.INSTANCE
                lastLiveSp.lastLiveId = liveId ?: data
                lastLiveSp.lastLiveAnchorId = anchorId
            } else {
                showToast(errorMsg)
            }
        }
        val isAnchor = TextUtils.equals(Const.getUserId(), anchorId)
        if (isAnchor) {
            // 主播端: 开启直播
            param.role = LiveRole.ANCHOR
            // 推流支持动态配置
            val pusherOptions = AliLiveMediaStreamOptions()
            param.mediaPusherOptions = pusherOptions
            param.title = binding.etTitle.text.toString()
        } else {
            // 观众端: 观看直播
            param.role = LiveRole.AUDIENCE
        }
        if (isAnchor) {
//            LivePrototype.getInstance().setup(this, param, callback)
            CustLiveProtoType.instance!!.setup(this, param, callback)
        } else {
//            LivePrototype.getInstance().setup(this, param, callback)
            CustLiveProtoType.instance!!.setup(this, param, callback)
        }
    }
}
